package com.atguigu.member.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.SocialUserTo;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.member.dao.MemberDao;
import com.atguigu.member.dao.MemberLevelDao;
import com.atguigu.member.entity.MemberEntity;
import com.atguigu.member.entity.MemberLevelEntity;
import com.atguigu.member.entity.MemberReceiveAddressEntity;
import com.atguigu.member.exception.PhoneExistExcption;
import com.atguigu.member.exception.UserNameExistExcption;
import com.atguigu.member.service.MemberService;
import com.atguigu.member.vo.MemberRegistVo;
import com.atguigu.member.vo.MemberUserLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Autowired
    private MemberDao memberDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 会员注册
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {

        MemberEntity memberEntity = new MemberEntity();
        //查询会员的默认等级
        MemberLevelEntity memberLevelEntity= memberLevelDao.selectMemberLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        /**
         *  检查用户名和手机号是否唯一
         *
         * 这里采用异常机制处理，如果查出用户名或手机号不唯一则向上抛出异常
         */

        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        //密码要加密存储
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        //其他的默认信息
        memberEntity.setNickname(vo.getUserName());

        //保存其他的信息
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistExcption{
        Integer count = this.getBaseMapper().selectCount(
                new LambdaQueryWrapper<MemberEntity>()
                        .eq(MemberEntity::getMobile, phone));
        if ( count>0 ) {
            throw new PhoneExistExcption();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistExcption{

        Integer count = this.getBaseMapper().selectCount(
                new LambdaQueryWrapper<MemberEntity>()
                        .eq(MemberEntity::getUsername, userName));
        if ( count>0 ) {
            throw new UserNameExistExcption();
        }

    }

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {

        String account = vo.getLoginAccount();
        String password = vo.getPassword();

        //查询数据库 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
        MemberEntity memberEntity = getOne(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getUsername, account)
                .or()
                .eq(MemberEntity::getMobile, account)
        );

        if (memberEntity==null) {
            //登录失败
            return null;
        } else {
            //获取数据库密码
            String passwordFromDb = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

            //进行比对
            //$2a$10$v8LcSjmwpDVh7LHUmNdVgu8ESrijtwO7D.xa6lQnxP4IwLo.5EcEK
            boolean matches = bCryptPasswordEncoder.matches(password, passwordFromDb);

            if (matches) {
                //登录成功
                return memberEntity;
            }
        }


        return memberEntity;
    }

    @Override
    public MemberEntity oauthLogin(SocialUserTo to) {
        //登录和注册合并逻辑

        MemberEntity memberEntity = this.getOne(
                new LambdaQueryWrapper<MemberEntity>()
                        .eq(MemberEntity::getSocialUid,
                                to.getId()));
        //判断用户是否已经注册
        if (memberEntity==null) {
            //未注册，第一次使用 封装社交信息
            String json = "";
            try {
                //获取社交信息
                Map<String,String> queryAccessToken = new HashMap<>();
                queryAccessToken.put("access_token",to.getAccess_token());

                Map<String,String> queryHeader = new HashMap<>();
                queryHeader.put("Content-Type","application/json;charset=UTF-8");
                //发送请求
                //https://gitee.com/api/v5/user?access_token={access_token}
                HttpResponse response = HttpUtils.doGet("https://gitee.com","/api/v5/user","get",queryHeader,queryAccessToken);
                json = EntityUtils.toString(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }

            memberEntity = new MemberEntity();
            memberEntity.setAccessToken(to.getAccess_token());
            memberEntity.setExpiresIn(to.getExpires_in());
            memberEntity.setSocialUid(to.getId());
            MemberLevelEntity memberLevelEntity = memberLevelDao.selectMemberLevel();
            memberEntity.setLevelId(memberLevelEntity.getId());


            //第三方信息 昵称，头像
            JSONObject jsonObject = JSON.parseObject(json);
            memberEntity.setNickname(jsonObject.getString("name"));
            memberEntity.setHeader(jsonObject.getString("avatar_url"));

            //保存到数据库
            this.save(memberEntity);

        }else {
            //已经注册
            memberEntity.setAccessToken(to.getAccess_token());
            memberEntity.setExpiresIn(to.getExpires_in());
            memberEntity.setSocialUid(to.getId());
            memberEntity.setNickname(to.getName());
            memberEntity.setHeader(to.getAvatar_url());

            this.update(memberEntity,
                    new LambdaUpdateWrapper<MemberEntity>()
                            .eq(MemberEntity::getSocialUid,
                                    to.getId()));
        }


        return memberEntity;
    }

}